package com.ruoyi.web.controller.api;

import java.util.List;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.estate.Repair;
import com.ruoyi.system.service.estate.IRepairService;

/**
 * 报修管理API Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/repair")
public class RepairApiController extends BaseController
{
    @Autowired
    private IRepairService repairService;

    /**
     * 查询当前用户的报修列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list()
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 设置分页信息
            startPage();
            
            // 查询用户关联的报修记录
            List<Repair> list = repairService.selectRepairListByUserId(userId);
            
            return getDataTable(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new TableDataInfo();
        }
    }

    /**
     * 获取报修详情
     */
    @Anonymous
    @GetMapping("/{repairId}")
    public AjaxResult getInfo(@PathVariable("repairId") Long repairId)
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 查询报修信息
            Repair repair = repairService.selectRepairById(repairId);
            
            // 验证报修是否属于当前用户
            if (repair != null && repair.getResidentId() != null && repair.getResidentId().equals(userId)) {
                return AjaxResult.success(repair);
            } else {
                return AjaxResult.error("无权访问该报修信息");
            }
        } catch (Exception e) {
            return AjaxResult.error("获取报修详情失败：" + e.getMessage());
        }
    }

    /**
     * 提交报修
     */
    @Anonymous
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody Repair repair)
    {
        try {
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 设置用户ID
            repair.setResidentId(userId);
            
            // 提交报修
            return toAjax(repairService.submitRepair(repair));
        } catch (Exception e) {
            return AjaxResult.error("提交报修失败：" + e.getMessage());
        }
    }

    /**
     * 取消报修
     */
    @Anonymous
    @PutMapping("/cancel/{repairId}")
    public AjaxResult cancel(@PathVariable Long repairId)
    {
        try {
            // 记录日志
            System.out.println("API调用: 取消报修, ID=" + repairId);
            
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            System.out.println("当前用户ID: " + userId);
            
            // 查询报修信息
            Repair repair = repairService.selectRepairById(repairId);
            
            // 验证报修是否存在
            if (repair == null) {
                System.out.println("报修不存在: 报修ID=" + repairId);
                return AjaxResult.error("报修不存在");
            }
            
            // 验证报修是否属于当前用户
            if (!repair.getResidentId().equals(userId)) {
                System.out.println("无权取消报修: 报修ID=" + repairId + ", 报修所属用户ID=" + repair.getResidentId() + ", 当前用户ID=" + userId);
                return AjaxResult.error("无权取消该报修");
            }
            
            // 验证报修状态是否为待处理
            if (!"0".equals(repair.getRepairStatus())) {
                System.out.println("报修状态不允许取消: 报修ID=" + repairId + ", 当前状态=" + repair.getRepairStatus());
                return AjaxResult.error("只能取消待处理的报修");
            }
            
            // 取消报修
            int result = repairService.cancelRepair(repairId);
            System.out.println("取消报修结果: 报修ID=" + repairId + ", 结果=" + result);
            
            return toAjax(result);
        } catch (Exception e) {
            System.out.println("取消报修异常: 报修ID=" + repairId + ", 错误信息=" + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("取消报修失败：" + e.getMessage());
        }
    }

    /**
     * 评价报修
     */
    @Anonymous
    @PutMapping("/evaluate")
    public AjaxResult evaluate(@RequestBody Map<String, Object> params)
    {
        try {
            // 记录日志
            System.out.println("API调用: 评价报修, 参数=" + params);
            
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            System.out.println("当前用户ID: " + userId);
            
            // 获取参数
            Long repairId = Long.valueOf(params.get("repairId").toString());
            String satisfaction = (String) params.get("satisfaction");
            String evaluation = (String) params.get("evaluation");
            
            System.out.println("评价参数: repairId=" + repairId + ", satisfaction=" + satisfaction + ", evaluation=" + evaluation);
            
            // 查询报修信息
            Repair repair = repairService.selectRepairById(repairId);
            
            // 验证报修是否存在
            if (repair == null) {
                System.out.println("报修不存在: 报修ID=" + repairId);
                return AjaxResult.error("报修不存在");
            }
            
            // 验证报修是否属于当前用户
            if (!repair.getResidentId().equals(userId)) {
                System.out.println("无权评价报修: 报修ID=" + repairId + ", 报修所属用户ID=" + repair.getResidentId() + ", 当前用户ID=" + userId);
                return AjaxResult.error("无权评价该报修");
            }
            
            // 验证报修状态是否为已完成
            if (!"2".equals(repair.getRepairStatus())) {
                System.out.println("报修状态不允许评价: 报修ID=" + repairId + ", 当前状态=" + repair.getRepairStatus());
                return AjaxResult.error("只能评价已完成的报修");
            }
            
            // 设置评价信息
            repair.setRepairStatus("4"); // 已评价
            repair.setUpdateBy(SecurityUtils.getUsername());
            repair.setSatisfaction(satisfaction); // 保存满意度评分
            repair.setEvaluation(evaluation); // 保存评价内容
            repair.setEvaluationTime(new Date()); // 设置评价时间
            
            // 更新报修信息
            int result = repairService.evaluateRepair(repair);
            System.out.println("评价报修结果: 报修ID=" + repairId + ", 结果=" + result);
            
            return toAjax(result);
        } catch (Exception e) {
            System.out.println("评价报修异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("评价报修失败：" + e.getMessage());
        }
    }
} 